import {defineStore} from "pinia";
import router from "@/router";

const WITHOUT_TAG_PATHS = ['/404', '/login']

export const useTagsStore = defineStore('tags', {
    persist: true,
    state: () => {
        return {
            tags: [],
            activeTag: '',
        }
    },
    getters: {
        activeIndex: (state): any => {
            return state.tags.findIndex((item: any) => item.path === state.activeTag)
        },
    },
    actions: {
        setActiveTag(path: any) {
            this.activeTag = path
        },
        setTags(tags: any) {
            this.tags = tags
        },
        addTag(tag: any) {
            this.setActiveTag(tag.path)
            if (WITHOUT_TAG_PATHS.includes(tag.path) || this.tags.some((item: any) => item.path === tag.path)) return
            this.setTags([...this.tags, tag])
        },
        removeTag(path: any) {
            if (path === this.activeTag) {
                if (this.activeIndex > 0) {
                    //@ts-ignore
                    router.push(this.tags[this.activeIndex - 1]?.path)
                } else {
                    //@ts-ignore
                    router.push(this.tags[this.activeIndex + 1]?.path)
                }
            }
            this.setTags(this.tags.filter((tag: any) => tag.path !== path))
        },
        //@ts-ignore
        removeOther(curPath = this.activeTag) {
            this.setTags(this.tags.filter((tag: any) => tag.path === curPath))
            if (curPath !== this.activeTag) {
                //@ts-ignore
                router.push(this.tags[this.tags.length - 1]?.path)
            }
        },
        removeLeft(curPath: any) {
            const curIndex = this.tags.findIndex((item: any) => item.path === curPath)
            const filterTags = this.tags.filter((item, index) => index >= curIndex)
            this.setTags(filterTags)
            if (!filterTags.find((item: any) => item.path === this.activeTag)) {
                //@ts-ignore
                router.push(filterTags[filterTags.length - 1]?.path)
            }
        },
        removeRight(curPath: any) {
            const curIndex = this.tags.findIndex((item: any) => item.path === curPath)
            const filterTags = this.tags.filter((item, index) => index <= curIndex)
            this.setTags(filterTags)
            if (!filterTags.find((item: any) => item.path === this.activeTag)) {
                //@ts-ignore
                router.push(filterTags[filterTags.length - 1]?.path)
            }
        },
        resetTags() {
            this.setTags([])
            this.setActiveTag('')
        },
    }

})
